<template>
	<view class="">
		
	</view>
</template>

<script>
	export default {
		data(){
			return:{
				
			}
		},
		props:{
			wsurl:{
				type:string,
				default:'',
				require:true
			}
		}
		onload(){
			// socket-------------------
			// 初始化WebSocket连接
			initWebSocket() {
				console.log("webscoket");
				this.socketTask = uni.connectSocket({
					url: this.wsurl,
					// success: () => {
						console.log('WebSocket连接成功');
						this.state = true
						this.startHeartbeat();
					},
					fail: (error) => {
						console.error('WebSocket连接失败', error);
					}
				});
			
				this.socketTask.onOpen((res) => {
					console.log('WebSocket 已打开', res);
				});
			
				this.socketTask.onMessage((res) => {
					console.log('收到服务器内容：' + res.data);
			
				});
			
				this.socketTask.onError((error) => {
					console.error('WebSocket 错误', error);
				});
			
				this.socketTask.onClose((res) => {
					console.log('WebSocket 已关闭', res);
					this.state = false
				});
			},
			
			// 发送心跳
			sendHeartbeat() {
				if (this.socketTask && this.socketTask.readyState === 1) {
					this.socketTask.send({
						data: JSON.stringify({
							type: '数据'
						})
					});
				}
			},
			
			// 开始心跳
			startHeartbeat() {
				setInterval(() => {
					this.sendHeartbeat();
				}, 5000); // 每5秒发送一次心跳
			},
			
			// ----------------------
		}
	}
</script>

<style scoped>

</style>